package com.juc.concurrency.jucExample.producerandconsumer;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 调整下对队列容量 生产者线程 消费者线程 观察输出
 * 当前参数情况是生产者速度大于消费者速度（线程数大于） 所以运行一段时间猴发现 队列容量基本上是在999 998附近
 * 如果消费者线程大与生产者 那么队列容量会很小 0 1 因为生产出来就被消费了
 */
public class ProducerConsumerDemo1 {

    private static LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>(1000);

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(200);
        for (int i = 0; i < 100; i++) {
            service.submit(new Productor(queue));
        }
        for (int i = 0; i < 10; i++) {
            service.submit(new Consumer(queue));
       }
    }

    static class Productor implements Runnable {
        private BlockingQueue queue;

        public Productor(BlockingQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    Random random = new Random();
                    int i = random.nextInt();
                    System.out.println("生产者" + Thread.currentThread().getName() + "生产数据" + i + "producer:queue-size:" + queue.size());
                    queue.put(i);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Consumer implements Runnable {
        private BlockingQueue queue;

        public Consumer(BlockingQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    Integer element = (Integer) queue.take();
                    System.out.println("消费者" + Thread.currentThread().getName() + "正在消费数据" + element + "consumer:queue-size:" + queue.size());
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
